package cn.itcase.saomiao;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import cn.itcase.saomiao.zxing.app.CaptureActivity;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findViewById(R.id.tv).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Open();
            }
        });
    }

    private void Open(){
        if (hasPermission(new String[]{Manifest.permission.CAMERA})) {
            //有权限 打开摄像头
            doOpenCamera();
        } else {
            requestPermission(CAMERA_CODE, new String[]{Manifest.permission.CAMERA});
        }
    }

    public static final int CAMERA_CODE = 2;
    private static final int REQUEST_QRCODE = 1;
    // 读取不同的权限 摄像头 通讯录
    public boolean hasPermission(String... permissions) {

        for (String permission : permissions){
            if(ContextCompat.checkSelfPermission(MainActivity.this,permission) != PackageManager.PERMISSION_GRANTED){
                return false;
            }
        }
        return true;
    }

    public void requestPermission(int code, String... permisions) {
        // 23 6.0
        if (Build.VERSION.SDK_INT >= 23) {
            requestPermissions(permisions,code);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

        switch (requestCode){

            // 如果返回的是 摄像头这一次 并且同意  就打开摄像头
            case CAMERA_CODE:
                if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    doOpenCamera();
                }
                break;
        }
    }

    public void doOpenCamera() {
        //需要把请求的权限传进来  2  1 2 3
        System.out.println("打开摄像头");
        Intent intent = new Intent(MainActivity.this, CaptureActivity.class);
        // 打开一个新的activity 是为了 result 拿到返回结果
        startActivityForResult(intent, REQUEST_QRCODE);
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            // 如果使我们请求的code 并且 成功
            case REQUEST_QRCODE:
                if (resultCode == Activity.RESULT_OK) {
                    // 弹出一下扫描结果
                    String code = data.getStringExtra("SCAN_RESULT");

                    Toast.makeText(MainActivity.this, code, Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }
}
